package com.hmall.search.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ISearchServiceImpl implements ISearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    private static final ObjectMapper MAPPER = new ObjectMapper();
    /*
    * 自动补全
    * */
    @Override
    public List<String> getSuggestion(String prefix) throws IOException {
        //1、准备Request
        SearchRequest request = new SearchRequest("item");
        //2、准备DSL
        request.source().fetchSource(new String[0],null);
        request.source().suggest(new SuggestBuilder()
                .addSuggestion("my_suggestion", SuggestBuilders.completionSuggestion("suggestion")
                .size(10)
                .skipDuplicates(true)
                .prefix(prefix)
                )
        );
        //3、发请求
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        //4、解析结果
        CompletionSuggestion suggestion = response.getSuggest().getSuggestion("my_suggestion");//获取suggest
        List<String> list = suggestion.getOptions().stream()
                .map(CompletionSuggestion.Entry.Option::getText)
                .map(Text::string)
                .collect(Collectors.toList());
        return list;
    }

    /*
    * 查询过滤（聚合）
    * */
    @Override
    public Map<String, List<String>> getFilters(RequestParams requestParams) throws IOException {
        //1准备request
        SearchRequest request = new SearchRequest("item");
        //2准备DSL
        //query条件
        buildBasicQuery(request,requestParams);//brand、category、minPrice、maxPrice
        request.source().size(0);//不要文档数据
        request.source().aggregation(//品牌聚合条件
                AggregationBuilders.terms("brandAgg").field("brand").size(20)
        );
        request.source().aggregation(//分类聚合条件
                AggregationBuilders.terms("categoryAgg").field("category").size(20)
        );
        //3发送请求
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        //4结果解析
        Aggregations aggregations = response.getAggregations();
        //4 1品牌聚合
        Terms brandAgg = aggregations.get("brandAgg");//根据名称获取品牌的聚合
        Map<String,List<String>> map = new HashMap<>();
        List<String> brandList = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        map.put("brand",brandList);//map  key：brand   value：brandList

        //4 2分类聚合
        List<String> categoryList = new ArrayList<>();
        Terms categoryAgg = aggregations.get("categoryAgg");
        List<? extends Terms.Bucket> buckets1 = categoryAgg.getBuckets();
        for (Terms.Bucket bucket : buckets1) {
            String key = bucket.getKeyAsString();
            categoryList.add(key);
        }
         map.put("category",categoryList);

        return map;
    }
    //基本搜索功能
    @Override
    public PageDTO<ItemDoc> getSearch(RequestParams requestParams) throws IOException {
        //1准备Request对象
        SearchRequest request = new SearchRequest("item");
        //2、query条件
        buildBasicQuery(request,requestParams);
        //2 1分页
        int page = requestParams.getPage();
        int size = requestParams.getSize();
        request.source().from((page-1)*size).size(size);
        //2 2排序
        String sortBy = requestParams.getSortBy();
        if("sold".equals(sortBy)){
            request.source().sort(sortBy, SortOrder.DESC);
        }else if("price".equals(sortBy)){
            request.source().sort(sortBy,SortOrder.ASC);
        }
        //2 3高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        //3发请求
        //4解析结果
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits searchHits = response.getHits();
        long total = searchHits.getTotalHits().value;//获取total
        SearchHit[] hits = searchHits.getHits();//数据
        List<ItemDoc> list = new ArrayList<>(hits.length);//存放数据
        for (SearchHit hit : hits) {//遍历数据
            String json = hit.getSourceAsString();//json类型
            //json转java
            ItemDoc itemDoc = MAPPER.readValue(json, ItemDoc.class);
            //获取高亮集合
            Map<String, HighlightField> map = hit.getHighlightFields();
            if(map != null && map.size() > 0){
                HighlightField field = map.get("name");
                String value = field.getFragments()[0].string();
                itemDoc.setName(value);
            }
            list.add(itemDoc);
        }

        return new PageDTO<>(total,list);//返回总数，item集合
    }

    @Autowired
    private ItemClient itemClient;
    //商品状态：上架（更新数据）
    @Override
    public void saveItemById(Long id) throws IOException {
        //1查询商品数据 根据id查找
        Item item = itemClient.queryItemById(id);
        //2准备Request
        IndexRequest request = new IndexRequest("item").id(id.toString());
        //3准备dsl
        request.source(MAPPER.writeValueAsString(new ItemDoc(item)), XContentType.JSON);
        //4发送请求
        restHighLevelClient.index(request,RequestOptions.DEFAULT);
    }


    //商品状态：下架（删除es的下架数据）
    @Override
    public void deleteById(Long id) throws IOException {
        //request

        DeleteRequest request = new DeleteRequest("item",id.toString());
        //发请求
        restHighLevelClient.delete(request,RequestOptions.DEFAULT);
    }

    //查询过滤（聚合）  中query ：过滤条件
    private void buildBasicQuery(SearchRequest request, RequestParams requestParams) {
        //key brand category price
        //创建boolean查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1.1key关键字
        String key = requestParams.getKey();
        if(StringUtils.isNotBlank(key)){
            //非空:根据关键字全文检索
            boolQueryBuilder.must(QueryBuilders.matchQuery("all",key));
        }else {
            //为空：没有条件查询所有
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }
        //1.2brand品牌：termQuery精确匹配
        String brand = requestParams.getBrand();
        if(StringUtils.isNotBlank(brand)){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand",requestParams.getBrand()));//terQuery精确匹配
        }
        //1.3category种类：termQuery精确匹配
        String category = requestParams.getCategory();
        if(StringUtils.isNotBlank(category)){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category",requestParams.getCategory()));
        }
        //1.4price价格：rangeQuery
        Long minPrice = requestParams.getMinPrice();//获取最大最小价格
        Long maxPrice = requestParams.getMaxPrice();
        //条件过滤
        if(minPrice != null && maxPrice != null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice  * 100).lte(maxPrice * 100));
        }

        //竞价排名
        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(
                boolQueryBuilder, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //isAD为true时，权重x100
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }
        );
        //放入request
        request.source().query(queryBuilder);
    }

}
